@using Microsoft.AspNetCore.Identity
@using SixLabors.ImageSharp
@using SixLabors.ImageSharp.Formats
@using SixLabors.ImageSharp.Processing

@inherits MudComponentBase
@inject IStringLocalizer<Users> L


<MudForm Model="@model" @ref="@form" Validation="@(modelValidator.ValidateValue)">
    <input For="@(() => model.Id)" @bind-value="model.Id" type="hidden" />
    <input For="@(() => model.ProfilePictureDataUrl)" @bind-value="model.ProfilePictureDataUrl" type="hidden" />
    <InputFile id="UploadPhoto" OnChange="UploadPhoto" hidden accept=".jpg, .jpeg, .png" />
    <MudGrid>
        <MudItem sm="12">
            <div class="d-flex justify-center">

                @if (string.IsNullOrEmpty(model.ProfilePictureDataUrl))
                {
                    <MudAvatar Style="height:128px; width:128px; font-size:2rem;">@model.UserName</MudAvatar>
                }
                else
                {
                    <MudAvatar Image="@model.ProfilePictureDataUrl" Style="height:128px; width:128px; font-size:2rem;" />
                }
                <MudTooltip Text="@L["Click upload a photo."]">
                    <MudIconButton HtmlTag="label"
                                   Color="MudBlazor.Color.Info"
                                   Icon="@Icons.Filled.PhotoCamera"
                                   for="UploadPhoto"></MudIconButton>
                </MudTooltip>
            </div>
        </MudItem>
        <MudItem xs="12" sm="6">
            <MudTextField For="@(() => model.Site)" @bind-Value="model.Site" Label="@L["Site"]" Variant="Variant.Text"></MudTextField>
        </MudItem>
        <MudItem xs="12" sm="6">
            <MudTextField For="@(() => model.UserName)" @bind-Value="model.UserName" Label="@L["User Name"]" Variant="Variant.Text"></MudTextField>
        </MudItem>
        <MudItem xs="12" sm="6">
            <MudTextField For="@(() => model.Email)" @bind-Value="model.Email" Label="@L["E-mail"]" Variant="Variant.Text"></MudTextField>
        </MudItem>
        <MudItem xs="12" sm="6">
            <MudTextField For="@(() => model.DisplayName)" @bind-Value="model.DisplayName" Label="@L["Display Name"]" Variant="Variant.Text"></MudTextField>
        </MudItem>
        @if (string.IsNullOrEmpty(model.Id))
        {
            <MudItem xs="12" sm="6">
                <MudTextField Immediate="true"
                          Label="@L["Password"]"
                          @bind-Value="model.Password"
                          For="@(() => model.Password)"
                          Variant="Variant.Text"
                          InputType="@PasswordInput"
                          Adornment="Adornment.End"
                          AdornmentIcon="@PasswordInputIcon"
                          Required="true"
                          RequiredError="@L["password is required!"]"
                          OnAdornmentClick="TogglePasswordVisibility" Class="mt-4" />
            </MudItem>
            <MudItem xs="12" sm="6">
                <MudTextField Immediate="true"
                          Label="@L["Confirm Password"]"
                          @bind-Value="model.ConfirmPassword"
                          For="@(() => model.ConfirmPassword)"
                          Variant="Variant.Text"
                          InputType="@PasswordInput"
                          Adornment="Adornment.End"
                          AdornmentIcon="@PasswordInputIcon"
                          Required="true"
                          RequiredError="@L["password is required!"]"
                          OnAdornmentClick="TogglePasswordVisibility" Class="mt-4" />
            </MudItem>
        }
        <MudItem xs="12" sm="6">
            <MudTextField For="@(() => model.PhoneNumber)" @bind-Value="model.PhoneNumber" Label="@L["Phone Number"]" Variant="Variant.Text"></MudTextField>
        </MudItem>
       <MudItem xs="12" sm="6">
            <MudText Typo="Typo.caption">@L["Status"]</MudText>
            <div class="d-fex">
                 <MudCheckBox For="@(() =>model.IsActive)" T="bool" @bind-Checked="model.IsActive" Label="@L["Is Active"]"></MudCheckBox>
            </div>
        </MudItem>
        <MudItem xs="12" sm="12">
            <MudText Typo="Typo.caption">@L["Assign Roles"]</MudText>
            <div class="d-fex">
                @for (int i = 0; i < _roles.Count; i++)
                {
                    var x = i;
                    <MudCheckBox For="@(() =>model.Checked)" T="bool" Checked="@_roles[x].value" Label="@_roles[i].key" CheckedChanged="@(s=>_roles[x].value=s)"></MudCheckBox>
                }
            </div>
        </MudItem>
    </MudGrid>
</MudForm>

@code {
    public class keyvalue
    {
        public string key { get; set; }
        public bool value { get; set; }
    }
    MudForm form = default!;
    private List<keyvalue> _roles { get; set; } = new();

    [Inject] private IUploadService _uploadService { get; set; } = default!;
    [Inject] private RoleManager<ApplicationRole> _roleManager { get; set; } = default!;
    UserFormModelValidator modelValidator = new();
    [EditorRequired][Parameter] public UserFormModel model { get; set; } = default!;
    [EditorRequired][Parameter] public EventCallback<UserFormModel> OnFormSubmit { get; set; }
    bool PasswordVisibility;
    InputType PasswordInput = InputType.Password;
    string PasswordInputIcon = Icons.Material.Filled.VisibilityOff;
    protected override async Task OnInitializedAsync()
    {
        var array = await _roleManager.Roles.Select(x => x.Name).ToListAsync();

        foreach (var role in array)
        {
            if (model.AssignRoles != null && model.AssignRoles.Contains(role))
            {
                _roles.Add(new() { key = role, value = true });
            }
            else
            {
                _roles.Add(new() { key = role, value = false });
            }
        }

    }
    void TogglePasswordVisibility()
    {
        @if (PasswordVisibility)
        {
            PasswordVisibility = false;
            PasswordInputIcon = Icons.Material.Filled.VisibilityOff;
            PasswordInput = InputType.Password;
        }
        else
        {
            PasswordVisibility = true;
            PasswordInputIcon = Icons.Material.Filled.Visibility;
            PasswordInput = InputType.Text;
        }
    }

    private async Task UploadPhoto(InputFileChangeEventArgs e)
    {
        var filestream = e.File.OpenReadStream();
        var imgstream = new MemoryStream();
        await filestream.CopyToAsync(imgstream);
        imgstream.Position = 0;
        using (var outStream = new MemoryStream())
        {
            using (var image = Image.Load(imgstream, out IImageFormat format))
            {
                image.Mutate(
                   i => i.Resize(new ResizeOptions() { Mode = ResizeMode.Crop, Size = new SixLabors.ImageSharp.Size(128, 128) }));
                image.Save(outStream, format);
                var filename = e.File.Name;
                var fi = new FileInfo(filename);
                var ext = fi.Extension;
                var result = await _uploadService.UploadAsync(new UploadRequest()
                    {
                        Data = outStream.ToArray(),
                        FileName = Guid.NewGuid().ToString() + ext,
                        Extension = ext,
                        UploadType = UploadType.ProfilePicture
                    });
                model.ProfilePictureDataUrl = result;
                //Do your validations here
                Snackbar.Add($"upload successfully", MudBlazor.Severity.Info);
            }
        }
    }
    public async Task Submit()
    {
        await form.Validate();
        if (form.IsValid)
        {
            model.AssignRoles = _roles.Where(x => x.value).Select(x => x.key).ToArray();
            await OnFormSubmit.InvokeAsync(model);
        }
    }
}
